/* Copyright (c) 2007-2008, Jeffrey R Griffin
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Jeffrey R Griffin nor the
 *       names of his contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Jeffrey R Griffin ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package net.visibleblue.android.app.dynamic;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import net.visibleblue.android.net.URLApkPackageHelper;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ContentURI;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

public class DynamicActivityHost extends Activity {

	static URLApkPackageHelper _urlApkPM = null;
	private ProgressDialog _progressDialog = null;
	private Handler _packageLoadHandler = new Handler() {
		private int _lastWhat = -1;

		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case URLApkPackageHelper.CONNECTED_MSG:
				_progressDialog.dismiss();
				_progressDialog = ProgressDialog.show(_progressDialog.getContext(), 
						"", "Connected!", true);
				break;
			case URLApkPackageHelper.PACKAGE_LOAD_MSG:
				double div = ((double)msg.arg1)/((double)msg.arg2);
				double prog = div*10000;
				if(_lastWhat==URLApkPackageHelper.PACKAGE_LOAD_MSG)
					_progressDialog.setProgress((int)prog);
				else
				{
					_progressDialog.dismiss();
					_progressDialog = ProgressDialog.show(_progressDialog.getContext(), 
							"", "Loading package...", false);
					_progressDialog.setProgress((int)prog);
					_progressDialog.show();
				}
				if(prog==10000)
				{
					_progressDialog.dismiss();
					_progressDialog = ProgressDialog.show(_progressDialog.getContext(), 
							"", "Verifying", true);
				}
				break;
			case URLApkPackageHelper.PACKAGE_VERIFY_MSG:
				_progressDialog.dismiss();
				if(msg.arg1==URLApkPackageHelper.PACKAGE_NOT_VERIFIED_ARG)
					throw new RuntimeException("The package signature could not be verified.");
				else
					DynamicActivityHost.this.SetUserVerificationLayout();
				break;
			}
			_lastWhat = msg.what;
		}
	};

	public DynamicActivityHost()
	{
		super();
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

//		test code
//		try
//		{
//			//getIntent().setData(new ContentURI("jar:http://visibleblue.net/HelloWorld.apk!/net.visibleblue.android.hello.HelloAndroid"));
//			//getIntent().setData(new ContentURI("jar:http://192.168.1.101/androidFiles/RestaurantSample.apk!/net.visibleblue.android.restaurant.RestaurantSample"));
//			//getIntent().putExtra("TableNumber", 6);
//		}
//		catch(Exception e){}

		setContentView(R.layout.main);
		SetBlur();

		if(_urlApkPM!=null)
		{
			try
			{
				String path = _urlApkPM.getCachedPackagePath();
				path = path.substring(path.lastIndexOf("/")+1);
				String data = getIntent().getData().toString();
				if(path.equals(data.substring(data.lastIndexOf("/", 
						data.indexOf("!/"))+1, data.indexOf("!/"))))
				{
					SetUserVerificationLayout();
					return;
				}
			}
			catch(FileNotFoundException fnfEx){}
		}

		try
		{
			_urlApkPM = new URLApkPackageHelper(getIntent().getData().toURI().toURL(), 
					this);
		}
		catch(MalformedURLException muriEx)
		{
			throw new RuntimeException(muriEx);
		}
		//work around dialog z-order bug/
		new Handler() {
			@Override
			public void handleMessage(Message msg)
			{
				_progressDialog = ProgressDialog.show(DynamicActivityHost.this, "", "Connecting...", true);
				_progressDialog.setWindow(DynamicActivityHost.this.getWindow());
				Thread work = new Thread() {
					public void run() {

						try
						{
							_urlApkPM.Connect(_packageLoadHandler);
							_urlApkPM.LoadPackage(_packageLoadHandler);
							_urlApkPM.VerifyPackage(_packageLoadHandler);
						}
						catch(IOException ioEx)
						{
							throw new RuntimeException(ioEx);
						}
					}
				};
				work.start();
			}
		}.sendMessage(new Message());
	}

	void SetUserVerificationLayout()
	{
		TextView text = (TextView)findViewById(R.id.text_view);
		Button runButton = (Button)findViewById(R.id.run_button);
		Button noButton = (Button)findViewById(R.id.no_button);
		if(_urlApkPM.getAlice()!=null)
		{
			text.setText(getText(R.string.text_view_text)+" "+
					_urlApkPM.getAlice().getContactName());
			text.setVisibility(View.VISIBLE);
			runButton.setVisibility(View.VISIBLE);
			noButton.setVisibility(View.VISIBLE);
		}
		else
		{
			text.setText(R.string.text_view_text_unsigned);
			text.setVisibility(View.VISIBLE);
			runButton.setVisibility(View.GONE);
			noButton.setText(R.string.run_button_text);
			noButton.setVisibility(View.VISIBLE);
		}
		noButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				finish();
			}
		});

		runButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				Intent intent = new Intent(DynamicActivityHost.this, HostCanvas.class);
				intent.putExtras(getIntent());
				startActivity(intent);
				finish();
			}

		});
	}

	private void SetBlur()
	{
		// Have the system blur any windows behind this one.
		getWindow().setFlags(WindowManager.LayoutParams.BLUR_BEHIND_FLAG,
				WindowManager.LayoutParams.BLUR_BEHIND_FLAG);

		// Apply a tint to any windows behind this one.  Doing a tint this
		// way is more efficient than using a translucent background.  Note
		// that the tint color really should come from a resource.
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.tintBehind = 0x60000820;
		getWindow().setAttributes(lp);
	}
}